package yxy.game.pm2.module.tip;

import org.redisson.api.RMap;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.game.base.redis.RedisManager;
import yxy.game.pm2.bean.db.dao.MySQLCacheDAO;
import yxy.game.pm2.bean.db.newDao.TipDAO;
import yxy.game.pm2.bean.db.po.TipPo;
import yxy.game.pm2.bean.module.BaseGameRedisLockBean;
import yxy.game.pm2.module.wuchao.WuchaoModule;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TipModule extends BaseGameRedisLockBean {

	// redis==========================================================================
	static public String key(String playerCode) {
		return String.format("PLAYER:%s:MODULE:TIP", playerCode);
	}

	static private RMap<String, Boolean> touch(String playerCode) throws RedisException {
		return RedisManager.client(redis()).getMap(key(playerCode));
	}

	public static boolean get(String playerCode, TipType type) {
		try {
			return touch(playerCode).get(type.getCode());
		} catch (Exception e) {
		}
		return false;
	}

	public static void set(String playerCode, TipType type, boolean open) {
		try {
			touch(playerCode).put(type.getCode(), open);
		} catch (RedisException e) {
		}
	}
	
	public static Map<String,Boolean> all(String playerCode){
		try {
			Map<String,Boolean> bucket = touch(playerCode).readAllMap();
			//redis中没数据的时候，从数据库取数据放入redis
			if(bucket.size() == 0){
				List<TipPo> tips = new ArrayList<>();

				if(tips !=null && tips.size() > 0){
					for (int i = 0; i < tips.size(); i++){
						bucket.put(tips.get(i).getDataId(),tips.get(i).isStatus());
					}
				}
			}
			return bucket;
		} catch (RedisException e) {
			e.printStackTrace();
		}
		return new HashMap<>();
	}

	//数据归档到数据库
	public static void saveToDB(String playerCode) {
		try {
			//存储
			List<TipPo> tipPoList = new ArrayList<>();
			if (touch(playerCode).isExists()) {
				Map<String, Boolean> tips = touch(playerCode).readAllMap();
				for (String key: tips.keySet()) {
					TipPo tipPo = new TipPo();
					tipPo.setPlayerCode(playerCode);
					tipPo.setDataId(key);
					tipPo.setStatus(tips.get(key));
					tipPoList.add(tipPo);
				}
				TipDAO.replace(tipPoList);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//从redis移走数据
	public static void removeAllFromRedis(String playerCode) throws RedisException {
		try {
			touchBucket(key(playerCode)).delete();
		} catch (RedisException e) {
			e.printStackTrace();
		}
	}
}
